package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.nio.BufferOverflowException;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //在这里应该是检查库存看够不够
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        //给买的商品id赋值
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(buyProductIds)) {
            buyProductIds = cartProductDtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
        }
        createOrderContext.setBuyProductIds(buyProductIds);
        //在给商品id拍一下序
        buyProductIds.sort(Long::compareTo);
        //首先判断所有商品的库存是否初试化
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);
        if (stocksForUpdate == null || stocksForUpdate.size() != buyProductIds.size()) {
            throw new BaseBusinessException("库存未初始化");
        }
        //sort一下两个链表使其一一对应
        cartProductDtoList.sort(Comparator.comparing(CartProductDto::getProductId));
        stocksForUpdate.sort(Comparator.comparing(Stock::getItemId));
        for (int i = 0; i < stocksForUpdate.size(); i++) {
            Stock stock = stocksForUpdate.get(i);
            CartProductDto buy = cartProductDtoList.get(i);
            long remainStock = stock.getStockCount();
            if (buy.getProductNum() > remainStock) {
                //抛异常，使其回滚
                throw new BaseBusinessException("库存不够");
            }
            //判断是否超过限购
            if (buy.getProductNum() >stock.getRestrictCount()) {
                throw new BaseBusinessException("超出限购数额");
            }
            //库存足够则修改
            Stock updateStock = new Stock();
            updateStock.setItemId(stock.getItemId());
            updateStock.setStockCount(remainStock - buy.getProductNum());
            updateStock.setLockCount((int) (stock.getLockCount() + buy.getProductNum()));
            int affectRows = stockMapper.updateByPrimaryKeySelective(updateStock);

            if (affectRows < 1) {
                //抛异常，使其回滚
                throw new BaseBusinessException("库存不够");
            }
        }

        return true;
    }
}